<template>
  <!-- 银行流水 -->
  <div class="jeecg-basic-table jeecg-basic-table-form-container">
    <a-form @keyup.enter.native="searchQuery">
      <a-row :gutter="8" type="flex">
        <a-col flex="135px">
          <a-form-item label="部门" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 18 }">
            <JDictSelectTag v-model:value="queryParam.ddlxIds" mode="multiple" :maxTagCount="0" dictCode="ddlxType@ddlxUser" placeholder="全部" :autofocus="false" @change="ddlxSelect" />
          </a-form-item>
        </a-col>

        <a-col flex="345px">
          <a-form-item l5bel="" :label-col="{ style: { width: '70px' } }">
            <a-select v-model:value="queryParam.today" default-value="0" id="today" style="width: 90px; margin-right: 5px" @change="todayChange">
              <a-select-option value="0">记账日期</a-select-option>
              <a-select-option value="1">出团日期</a-select-option>
              <a-select-option value="2">审核日期</a-select-option>
            </a-select>
            <a-date-picker v-model:value="queryParam.jzsjBegin" :disabled-date="disabledStartDate" valueFormat="YYYY-MM-DD" placeholder="" style="width: 110px; padding:4px" /> ~
            <a-date-picker v-model:value="queryParam.jzsjEnd" :disabled-date="disabledEndDate" valueFormat="YYYY-MM-DD" placeholder="" style="width: 110px; padding: 4px" />
          </a-form-item>
        </a-col>

        <a-col flex="120px">
          <a-form-item label="状态" :label-col="{ style: { width: '40px' } }">
            <a-select name="stat" id="stat" v-model:value="queryParam.shbj" :disabled="shbjDisabled" class="w80" placeholder="全部" :showArrow="false" :allowClear="true" @change="shbjSelect">
              <a-select-option value="0">未审</a-select-option>
              <a-select-option value="1">已审</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col flex="165px">
          <a-form-item label="银行账户" :label-col="{ style: { width: '70px' } }">
            <JDictSelectTag 
              v-model:value="queryParam.bankIds" 
              mode="multiple" 
              dictCode="chee_bank,djm,id,1=1 order by sort"
              placeholder="全部" 
              :maxTagCount="0"
              :dropdownStyle="{ width: '200px', overflow: 'auto' }"
              :dropdownMatchSelectWidth="false"
              :allowClear="true"
              :showArrow="false"
              :showSearch="true"
            />
          </a-form-item>
        </a-col>

        <a-col flex="110px">
          <a-form-item label="类型" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 17 }">
            <a-select v-model:value="queryParam.sflx" id="sflx" class="w80" placeholder="全部" :showArrow="false" :allowClear="true">
              <a-select-option value="1">收入</a-select-option>
              <a-select-option value="2">支出</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col flex="140px">
          <a-form-item label="分解" :label-col="{ style: { width: '40px' } }" >
            <a-select v-model:value="queryParam.uncouple" id="sflx" class="w80" placeholder="全部" :showArrow="false" :allowClear="false">
              <a-select-option value="1">系统流水</a-select-option>
              <a-select-option value="2">订单流水</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col flex="100px">
          <a-form-item label="部门账户" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ span: 17 }">
            <a-checkbox :checked="queryParam.bankOid === '1'" @change="changebankOidChecked"></a-checkbox>
          </a-form-item>
        </a-col>
        
        <a-col flex="auto" style="float: right; width: 100px">
          <span style="float: right; overflow: hidden" class="table-page-search-submitButtons">
            <a-button type="primary" @click="searchQuery" preIcon="ant-design:search">查询</a-button>
          </span>
        </a-col>
      </a-row>

      <a-row :gutter="8">
        <a-col flex="135px">
          <a-form-item label="划转" :label-col="{ style: { width: '40px' } }">
            <a-select v-model:value="queryParam.insider" id="insider" placeholder="全部" :showArrow="false" :allowClear="true" :disabled="insiderDisabled" @change="insiderSelect">
              <a-select-option value="0">不含</a-select-option>
              <a-select-option value="1">仅含</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>

        <a-col flex="245px">
          <a-form-item label="金额" :label-col="{ style: { width: '40px' } }" >
            <a-input-number v-model:value.number="queryParam.beginJe" class="w-90px min-w-60px" /> -
            <a-input-number v-model:value.number="queryParam.endJe" class="w-90px min-w-60px" />
          </a-form-item>
        </a-col>

        <a-col flex="180px">
          <a-form-item label="订单号" :label-col="{ style: { width: '55px' } }" >
            <a-input placeholder="" v-model:value.trim="queryParam.orderId"></a-input>
          </a-form-item>
        </a-col>

        <a-col flex="205px">
          <a-form-item label="对方户名" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ span: 17 }">
            <a-input placeholder="" v-model:value.trim="queryParam.dfhm"></a-input>
          </a-form-item>
        </a-col>

        <a-col flex="200px">
          <a-form-item label="备注" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 17 }">
            <a-input placeholder="" v-model:value.trim="queryParam.bz"></a-input>
          </a-form-item>
        </a-col>

        <a-col flex="auto" style="float: right; width: 110px">
          <span style="float: right; overflow: hidden" class="table-page-search-submitButtons">
            <a-button type="primary" @click="caleQueryDate('1')" preIcon="ant-design:calendar-twotone">昨天</a-button>
            <a-button type="primary" @click="caleQueryDate('2')" preIcon="ant-design:field-number-outlined">本周</a-button>
            <a-button type="primary" @click="caleQueryDate('3')" preIcon="ant-design:insert-row-above-outlined">本月</a-button>
          </span>
        </a-col>
      </a-row>
    </a-form>
  </div>

  <!-- table区域-begin -->
  <BasicTable @register="registerTable" :onRowClick="handleClick" :onRowDbClick="handleDblclick" :rowClassName="rowClassName" :loading="loading">
    <!--插槽:table标题-->
    <template #tableTitle>
      <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 新增 </a-button>
      <a-button type="primary" color="warning" preIcon="ant-design:edit-outlined" @click="handleEdit" :disabled="editDisabled"> {{ editDisabled ? '查看' : '编辑' }} </a-button>
      <a-button type="primary" color="error" preIcon="ant-design:delete-twotone" @click="handleDelete" :disabled="deleDisabled"> 删除 </a-button>
      <j-upload-button type="primary" color="success" preIcon="ant-design:arrow-up-outlined" @click="onImportXls" class="ml-4">导入</j-upload-button>
      <a-button type="primary" color="warning" preIcon="ant-design:arrow-down-outlined" @click="onExportXls"> 导出 </a-button>
      <a-button type="primary" color="success" preIcon="ant-design:sisternode-outlined" @click="handleDecompose" :disabled="decomposeDisabled"> 分解明细 </a-button>
      <!--a-button type="primary" color="success" preIcon="ant-design:sisternode-outlined" @click="handleBankBusinessOrder" :disabled="businessOrderDisabled"> 订单明细 </a-button-->
      <!--a-button type="primary" color="success" preIcon="ant-design:sisternode-outlined" @click="handleBankAccountFlow" :disabled="accountFlowDisabled"> 收支审核 </a-button-->
      <!--a-button type="primary" color="success" preIcon="ant-design:book-twotone" @click="handleDecompose"> 模板 </!--a-button-->
    </template>
    <template #orderTmp="{text, record}">
      <div v-if="record.sflx == '1' && record.uncouple == '1'" style="margin: -8px; ">
        <div class="text-right text-red-500" style="font-size: 12px; height: 16px; line-height: 16px; padding-right: 10px;">已 {{ formatAmount(record.yshcn) }} 元</div>
        <div class="text-right text-green-500" style="font-size: 12px; height: 16px; line-height: 16px; padding-right: 10px;">未 {{ formatAmount(record.fjcn) }} 元</div>
      </div>
      <span v-else>{{text}}</span>
    </template>
  </BasicTable>
  <!-- table区域-end-->

  <!-- 表单区域-->
  <BankRunningModal @register="registerBankRunningAdd" @success="modalFormOk" :canResize="true"></BankRunningModal>
  <BankDecomposeList @register="registerBankDecomposeList" @success="modalFormOk" :canResize="true"></BankDecomposeList>
  <BankBusinessOrder @register="registerBankBusinessOrder" @success="modalFormOk" :canResize="true"></BankBusinessOrder>
  <BankAccountFlow @register="registerBankAccountFlow" @success="modalFormOk" :canResize="true"></BankAccountFlow>
</template>

<script lang="ts" setup name="bankRunning-list">
  import { ref, computed, unref, reactive, toRaw } from 'vue';
  import { BasicTable, TableAction, ActionItem, BasicColumn } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { render } from '/@/utils/common/renderUtils';
  import { bankRunninglist, deleteBankRunning, getImportUrl, getExportUrl } from '/@/views/full/bank/types/bank.api';
  import { dateFormat, filterObj, formatAmount } from '/@/utils/common/compUtils';
  import { useMethods } from '/@/hooks/system/useMethods';

  import dayjs from 'dayjs';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import BankRunningModal from './modules/BankRunningModal.vue';
  import BankDecomposeList from './modules/BankDecomposeList.vue';
  import BankBusinessOrder from './modules/BankBusinessOrder.vue';
  import BankAccountFlow from './modules/BankAccountFlow.vue';

  import { debounce, throttle } from 'lodash-es';
  //----------定义变量 开始-------------------------------------------------------------
  const insiderDisabled = ref<boolean>(false);
  const shbjDisabled = ref<boolean>(false);
  const editDisabled = ref<boolean>(true);
  const deleDisabled = ref<boolean>(true);
  const decomposeDisabled = ref<boolean>(true);
  const loading = ref<boolean>(false);

  //定义查询表单，查询条件
  const queryParam = reactive<any>({
    ddlxIds: [],
    today: '0', //未审
    jzsjBegin: dayjs().subtract( 3, 'month').startOf('month').format('YYYY-MM-DD'),
    jzsjEnd: dayjs().add(0, 'month').endOf('month').format('YYYY-MM-DD'),
    shbj: '',
    uncouple: '1',
    bankIds: [],
    userIds: [],
    sflx: null,
    insider: null,
    beginJe: '',
    endJe: '',
    orderId: '',
    dfhm: '',
    bankOid: '1'
  });
  //----------定义变量--结束-------------------------------------------------------------

  //----------流水列表--组件-------------------------------------------------------------
  const statusFmt = ({ text }: { text: any }) => {
    if (text && text !== '合计') {
      const color = text == '0' ? 'green' : text == '1' ? 'red' : 'green';
      const value = text == '0' ? '未审' : text == '1' ? '已审' : '未审';
      return render.renderTag(value, color);
    }
  };

  // 部门翻译
  const ddlxFmt = ({ text, record }) => {
    if (record.uncouple == '1') {
      if (record.sflx == '2') {
        return render.renderTag("分摊", "orange");
      } else {
        return render.renderTag("分解", "orange");
      }
    } else if (record.orderId && record.orderId.indexOf('-9') > 0) {
      if (!text) {
        return render.renderTag("划转", "purple");
      } else {
        return render.renderTag(render.renderDict(text, 'ddlxType'), "green");
      }
    } else if (!text) {
      return text;
    } else {
      return render.renderTag(render.renderDict(text, 'ddlxType'), "green");
    }
  };

  const orderFmt = ({ text, record }) => {
    if (record.sflx == '1' && record.uncouple == '1') {
      //fjcn = 总数分解数量， yshcn = 已审分解数量
      let fjcn = 0, yshcn = 0;
      if (record.fjcn != null) {
        fjcn = record.fjcn
      }
      if (record.yshcn != null) {
        yshcn = record.yshcn
      }
      return "己"+ yshcn + "元，未" + fjcn + "元";
    } else {
      return text
    }
  };

  // 收付方式翻译
  const sffsFmt = ({ text, record }) => {
    if (!text) {
      return ''
    }
    let color : String[] = ['', 'red', '', 'blue', 'purple', 'orange'];
    return render.renderTag(render.renderDict(text, 'sffsType'), color[text])
  };

  //订单列表 - 表头
  const columns: BasicColumn[] = [
    { title: '状态', align: 'center', dataIndex: 'shbj', width: 55, customRender: statusFmt },
    { title: '部门', align: 'center', dataIndex: 'ddlx', width: 70, customRender: ddlxFmt },
    { title: '订单号', align: 'center', dataIndex: 'orderId', width: 112, ellipsis: true, className: 'text-red-500', slots: { customRender: 'orderTmp' } },
    { title: '银行账户', align: 'left', dataIndex: 'djm', width: 120 },
    { title: '方式', align: 'center', dataIndex: 'sffs', width: 43, customRender: sffsFmt },
    { title: '记账日期', align: 'center', dataIndex: 'jzsj', width: 93 },
    { title: '收入', align: 'right', dataIndex: 'srje', width: 91, className: 'text-red-500' },
    { title: '支出', align: 'right', dataIndex: 'zcje', width: 91, className: 'text-green-500' },
    { title: '对方户名', align: 'left', dataIndex: 'dfhm', width: 110 },
    { title: '录入人', align: 'center', dataIndex: 'lrr', width: 60 },
    { title: '录入时间', align: 'center', dataIndex: 'lrsj', width: 105 },
    { title: '审核人', align: 'center', dataIndex: 'gxr', width: 60 },
    { title: '审核时间', align: 'center', dataIndex: 'gxsj', width: 105 },
    { title: '备注', align: 'left', dataIndex: 'bz', width: 190, ellipsis: true, fixed: 'right' },
  ];

  // 列表页面公共参数、方法
  const { prefixCls, tableContext, onImportXls } = useListPage({
    designScope: 'bankrunning-list',
    tableProps: {
      api: bankRunninglist,
      columns: columns,
      size: 'small',
      showTableSetting: false,
      showIndexColumn: true, //行号
      showActionColumn: false,
      useSearchForm: false,
      resizeHeightOffset: 40,
      showSummary: true,
      summaryFunc: handleSummary,
      beforeFetch: (params) => Object.assign(params, filterObj(queryParam)),
    },
    importConfig: {
      url: getImportUrl,
      success: () => reload(),
    },
  });

  //注册table数据
  const [registerTable, { reload, setProps, getRawDataSource }] = tableContext;

  const { handleImportXls, handleExportXls } = useMethods();
  //----------流水列表--组件-------------------------------------------------------------

  //----------流水列表--事件-----------------------------------------------------------
  //---列表查询相关函数----------------------------------------------------------------
  /* 日期参数 */
  function disabledStartDate(beginDate) {
    let endDate = queryParam.jzsjEnd;
    if (!beginDate || !endDate) {
      return false;
    }

    beginDate = dayjs(beginDate).format('YYYY-MM-DD')
    // true 禁用 false 可用
    return dayjs(beginDate).valueOf() > dayjs(endDate).valueOf();
  }

  function disabledEndDate(endDate) {
    const beginDate = queryParam.jzsjBegin;
    if (!endDate || !beginDate) {
      return false;
    }
    endDate = dayjs(endDate).format('YYYY-MM-DD')
    return dayjs(beginDate).valueOf() > dayjs(endDate).valueOf();
  }

  function todayChange() {
    // if (queryParam.today == '1') {
    //   queryParam.shbj = '1';
    // } else {
    //   queryParam.shbj = '0';
    // }
  }

  function searchQuery() {
    //filterObj
    let params = toRaw(filterObj(queryParam));
    if (typeof params.shbj === 'undefined') {
      params.shbj = '';
    }
    setProps({ searchInfo: params });
    reload();
  }

  function searchReset() {
    Object.assign(queryParam, { ddlxIds: [], ddzt: '', ywlx: '' });
    reload();
  }

  function caleQueryDate(type) {
    if( type === '1') {
      //昨天
      queryParam.jzsjBegin = dayjs().subtract( 1, 'day').format('YYYY-MM-DD')
      queryParam.jzsjEnd = dayjs().subtract( 1, 'day').format('YYYY-MM-DD')
    } else if(type === '2') {
      //本周
      queryParam.jzsjBegin = dayjs().startOf('week').add(0, 'day').format('YYYY-MM-DD')
      queryParam.jzsjEnd = dayjs().startOf('week').add(6, 'day').format('YYYY-MM-DD')
    } else if(type === '3') {
      //本月
      queryParam.jzsjBegin = dayjs().startOf('month').format('YYYY-MM-DD')
      queryParam.jzsjEnd = dayjs().endOf('month').format('YYYY-MM-DD')
    } else if(type === '4') {
      //上月
      queryParam.jzsjBegin = dayjs().add(-1, 'month').startOf('month').format('YYYY-MM-DD')
      queryParam.jzsjEnd = dayjs().add(-1, 'month').endOf('month').format('YYYY-MM-DD')
    }
    searchQuery();
  }

  function handleSummary(tableData: Recordable[]) {
    const res = getRawDataSource();
    if (res) {
      return getRawDataSource().summary;
    } else {
      return [];
    }
  }

  //新增订单
  const [registerBankRunningAdd, { openModal: openBankRunning }] = useModal();

  //单击行
  let selectRows = reactive<any>({ id: '', parentId: '' });
  let k = false;
  function handleClick(record) {
    if (k) {
      // 防抖 k = true 时候，退出操作；
      return;
    } else {
      // ；
      k = true;
    }
    // 
    if (selectRows.id == record.id) {
      selectRows.id = '';
      selectRows.parentId = '';
      editDisabled.value = true;
      deleDisabled.value = true;
      decomposeDisabled.value = true;
    } else {
      handleButton(record);
    }

    setTimeout(function() {
      k = false;
    }, 300);

  }

  //双击行
  function handleDblclick(record) {
    handleButton(record);
    handleEdit();
  }

  //列表按钮
  function handleButton(record) {
    selectRows.id       = record.id;
    selectRows.parentId = record.parentId || '';
    selectRows.orderId  = record.orderId || '';

    let shbj = !!record && record.shbj ? record.shbj : "";
    if (shbj == '1') {
      editDisabled.value = false;
      deleDisabled.value = true;
    } else {
      editDisabled.value = false;
      deleDisabled.value = false;
    }

    // 是划转
    let orderId = !!record && record.orderId ? record.orderId : "";
    //console.info(orderId, orderId.indexOf('-9'));
    if (!!orderId && orderId.indexOf('-9') > 0) {
      editDisabled.value = false;
      deleDisabled.value = false;
    }
    
    // 查看明细
    if ("1,2,3".indexOf(record.uncouple) >= 0) {
      decomposeDisabled.value = false;
    } else {
      decomposeDisabled.value = true;
    }
  }

  function handleCreate() {
    openBankRunning(true, { isUpdate: false });
  }

  function handleEdit() {
    let record = { id: selectRows.id };
    openBankRunning(true, { isUpdate: true, record });
  }

  //新增编辑成功后，刷新列表
  function modalFormOk() {
    searchQuery();
  }

  /**
   * 删除事件
   */
  async function handleDelete() {
    let record = { id: selectRows.id, orderId: selectRows.orderId };
    await deleteBankRunning(record, reload);
  }

  function onExportXls() {
    searchQuery();
    handleExportXls('银行流水', getExportUrl, filterObj(queryParam));
  }

  //部门下接框
  function ddlxSelect() {
    //有选择操作
    // if (queryParam.ddlxIds && queryParam.ddlxIds.length > 0) {
    //   shbjDisabled.value = true;
    //   queryParam.shbj = '1';
    //   insiderDisabled.value = true;
    //   queryParam.insider = '0';
    // } else {
    //   shbjDisabled.value = false;
    //   queryParam.shbj = '';
    //   insiderDisabled.value = false;
    //   queryParam.insider = '0';
    // }
  }

  //是否包含划转流水数据：0 不含 1 仅含
  function insiderSelect() {
    if (queryParam.insider == '0') {
      shbjDisabled.value = false;
      queryParam.shbj = null;
    } else if (queryParam.insider == '1') {
      shbjDisabled.value = true;
      queryParam.shbj = null;
    } else {
      shbjDisabled.value = false;
      queryParam.shbj = null;
    }
  }

  //定义行样式
  function rowClassName(record, index) {
    let className = '';
    if (record.id === selectRows.id) {
      className = 'row-selected';
    }
    return className;
  }

  //审核
  function shbjSelect() {
    // if ( queryParam.shbj == "0" ) {
    //   insiderDisabled.value = false;
    //   queryParam.insider = null;
    // } else if ( queryParam.shbj == "1" ) {
    //   insiderDisabled.value = true;
    //   queryParam.insider = "1";
    // } else {
    //   insiderDisabled.value = false;
    //   queryParam.insider = null;
    // }
  }

  // 不含内账
  function changebankOidChecked(e) {
    queryParam.bankOid = e.target.checked ? '1' : '0';
  }

  //----------分解表单--组件----------------------------------------------------------
  //分解明细
  const [registerBankDecomposeList, { openModal: openBankDecomposeList }] = useModal();
  function handleDecompose() {
    let record = {  };
    if (selectRows.parentId) {
      record = {
        id: selectRows.parentId,
        sid: selectRows.id,
      }
    } else {
      record = {
        id: selectRows.id,
      }
    }
    openBankDecomposeList(true, { isUpdate: true, record });
  }

  //订单明细
  const [registerBankBusinessOrder, { openModal: openBankBusinessOrder }] = useModal();
  function handleBankBusinessOrder() {
    let record = { id: selectRows.id };
    openBankBusinessOrder(true, { isUpdate: true, record });
  }

  //收支审核
  const [registerBankAccountFlow, { openModal: openBankAccountFlow }] = useModal();  
  function handleBankAccountFlow() {
    let record = { id: selectRows.id };
    openBankAccountFlow(true, { isUpdate: true, record });
  }
  //----------分解表单--组件-----------------------------------------------------------
</script>
<style lang="less" scoped>
  .table-page-search-submitButtons{
    button {
      margin-left: 5px;
    }
  }
  :deep(.ant-input-number) {
    min-width: 60px !important;
  }
  :deep(.ant-input-number .ant-input-number-input) {
    padding: 0 5px !important;
  }
  :deep(.ant-select-multiple .ant-select-selection-placeholder) {
    inset-inline-start: 5px
  }
</style>
